package com.fhz.day006;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.res.Configuration;
import android.util.DisplayMetrics;

import androidx.annotation.NonNull;

/**
 * 时间:2022/3/27
 *
 * @author msfeng
 * 简述: 屏幕适配的类
 */
public class Density {
    //设计尺寸
    public static final int WIDTH = 360;
    //屏幕密度
    public static float appDensity ;
    //文字密度
    public static float appScaleDensity ;

    public static void setDensity(Application application, Activity activity){
        //当前设备的屏幕信息
        DisplayMetrics appDisplayMetrics = application.getResources().getDisplayMetrics();
        if(appDensity == 0){
            appDensity = appDisplayMetrics.density;
            appScaleDensity = appDisplayMetrics.scaledDensity;

            //对字体变化的调整
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(@NonNull Configuration configuration) {
                    if (configuration != null && configuration.fontScale > 0 ){
                            appScaleDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });

        }

        float targetDensity = appDisplayMetrics.widthPixels / WIDTH;
        float targetScaleDensity = targetDensity * (appScaleDensity / appDensity);

        //设置目标的密度
        DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();
        displayMetrics.density = targetDensity;
        displayMetrics.scaledDensity = targetScaleDensity;
        displayMetrics.densityDpi = (int) (targetDensity * 160);

    }
}



















